//
//  QRCodeMyCardViewController.swift
//  LBWeibo
//
//  Created by 李博 on 15/7/1.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import FFAutoLayout

class QRCodeMyCardViewController: UIViewController {

    lazy var iconView = UIImageView()
    
    override func loadView() {
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(iconView)
        iconView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 200, height: 200))
        iconView.backgroundColor = UIColor.lightGrayColor()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        iconView.image = generateQRCodeImage()
        
    }
    
    private func generateQRCodeImage() -> UIImage {
        
        //1. 建立二维码滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        
        //2. 设置初始值
        qrFilter.setDefaults()
        
        //3. 通过KVC 设置滤镜信息
        qrFilter.setValue("我是大少爷".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        
        //4.获取结果
        let ciImage = qrFilter.outputImage
        
        //5.生成图片
        print(ciImage.extent)
        
        //6. 放大图片
        let transform = CGAffineTransformMakeScale(20, 20)
        let transformImage = ciImage.imageByApplyingTransform(transform)
        print("转换的图像大小 \(transformImage.extent)")
        //7.颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(transformImage, forKey: "inputImage")
        //前景色
        colorFilter.setValue(CIColor(color: UIColor.blackColor()), forKey: "inputColor0")
        //背景色
        colorFilter.setValue(CIColor(color: UIColor.whiteColor()), forKey: "inputColor1")
        
        let resultImage = colorFilter.outputImage
        let avatar = UIImage(named: "avatar")!
        
        return insertAvatarImage(UIImage(CIImage: resultImage), avatar: avatar)
    }
    
    /// 在二维码图像中间增加一个头像
    private func insertAvatarImage(image: UIImage, avatar: UIImage) -> UIImage {
        
        //1. 开启绘图上下文，和image相同大小
        UIGraphicsBeginImageContext(image.size)
        
        //2. 绘图
        let rect = CGRect(origin: CGPointZero, size: image.size)
        image.drawInRect(rect)
        
        //添加头像
        let w = rect.width * 0.15
        let x = (rect.width - w) * 0.5
        let y = (rect.height - w) * 0.5
        avatar.drawInRect(CGRect(x: x, y: y, width: w, height: w))
        
        //3. 取得结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        //4. 关闭绘图上下文
        UIGraphicsEndImageContext()
        
        return result
    }
}
